package services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class AvatarServlet
 */
@WebServlet("/AvatarServlet")
@MultipartConfig
public class AvatarServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AvatarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		String cmd=getParameter(request, Protocol.CMD);
		String cmd=request.getParameter(Protocol.CMD);

		if(cmd.equals(Protocol.UPLOAD)){
			//Cập nhật avatar
			String tenDangNhap=getParameter(request, Protocol.NGUOI_DUNG);
			String realPath = request.getRealPath("/");
			String path=realPath+Protocol.DIR_AVATAR+"/"+tenDangNhap+".png";
			File file=new File(path);
			FileOutputStream fos=new FileOutputStream(file);
			Part pFile = request.getPart("file");
			InputStream is = request.getPart(pFile.getName()).getInputStream();
			
			byte[] b = new byte[1024];
			int len=-1;
			while((len=is.read(b))!=-1){
				fos.write(b,0,len);
			}
			fos.flush();
			fos.close();
			is.close();
			
		}
		else if(cmd.equals(Protocol.DOWNLOAD)){
			//Cache avatar về máy client
			ServletContext ctx = getServletContext();
			String tenDangNhap=getParameter(request, Protocol.NGUOI_DUNG);
			String path=Protocol.DIR_AVATAR+"/"+tenDangNhap+".png";
		
			
			InputStream is = ctx.getResourceAsStream(path);
			if(is!=null){
				String contentType = getServletContext().getMimeType(path);
				response.setContentLength(is.available());
				response.setContentType(contentType);
				response.setHeader("Content-Disposition", "attachment;filename=" + tenDangNhap+".png");
	
				int read = 0;
				byte[] bytes = new byte[1024];
				OutputStream os = response.getOutputStream();
	
				while ((read = is.read(bytes)) != -1) {
					os.write(bytes, 0, read);
				}
				os.flush();
				os.close();
				System.out.println("avatar Download"+path);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
